package com.JingYan.global;


import com.JingYan.annotation.BaseResponse;
import com.JingYan.domain.AjaxResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author DongJiaQi
 * @create 2022/12/6 11:35
 * @Description: 全局封装类
 */
@RestControllerAdvice(annotations = BaseResponse.class)
public class ServerResponseAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 判断是否哪些需要做封装
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        return true;
    }

    /**
     * 封装操作
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof AjaxResult) {
            return body;
        }
        // 不是 Result 类型，就用 Result 包装后返回
        return AjaxResult.success("操作成功",body);
    }
}
